<template>
	<view class="page">
		
		<view class="container">
			<view class="title">
				注册
			</view>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item required label="姓名" name="username">
					<uni-easyinput type="text" name="username" v-model="formData.username" placeholder="请输入用户名" />
				</uni-forms-item>
				<uni-forms-item required name="password" label="密码">
					<uni-easyinput v-model="formData.password" name="password" type="password" placeholder="请输入密码" />
				</uni-forms-item>
				<uni-button type="primary" round @click="addUser">注册</uni-button>
			</uni-forms>
			<view class="register" @click="login">
				已有账号去登录
			</view>
		</view>
	</view>
</template>


<script>
	export default {
		name: 'register',
		data() {
			return {
				formData: {
					username: '',
					password: ''
				},
				rules: {
					// 对name字段进行必填验证
					username: {
						rules: [{
								required: true,
								errorMessage: '请输入用户名',
							},
							{
								minLength: 1,
								maxLength: 6,
								errorMessage: '用户名长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					password: {
						rules: [{
								required: true,
								errorMessage: '请输入密码',
							},
							{
								minLength: 4,
								maxLength: 8,
								errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',

							}
						]
					}
				}

			}
		},
		methods: {
			// 用户注册
			addUser() {
				var username = this.formData.username;
				var password = this.formData.password;
				console.log(username);
				this.$refs.form.validate().then(res => {
					uni.request({
						url: 'http://localhost:3000/api/user/addUser',
						method: 'POST',
						data: {
							username: this.formData.username,
							password: this.formData.password,
						},

						success: (res) => {
							console.log(res);
							uni.showToast({
								title: "注册成功"
							})
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}
					});
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			login(){
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}
		}
	}
</script>
<style>
	.page {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-image: url("https://pic.imgdb.cn/item/64994b5f1ddac507cc03af21.jpg");
		background-size: cover;
		background-position: center;
	}


	.container {
		text-align: center;
		padding: 40px;
		width: 300px;
		height: auto;
		/* 可根据内容高度自动调整 */
		background-color: #f5f5f5;
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}
	
	.title{
		margin-bottom: 40px;
		font-size: 28px;
	}
	.register{
		margin-top: 10px;
		font-size: 10px;
	}
</style>